package com.lin.mybatisdubbomysql.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.lin.mybatisdubbomysql.config.properties.DatabaseTwoProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @author 九分石人
 */
@Configuration
@MapperScan(basePackages = "com.lin.mybatisdubbomysql.dal.mapper.databasetwo", sqlSessionTemplateRef = "SqlSessionTemplateTwo")
@EnableConfigurationProperties(DatabaseTwoProperties.class)
public class DatabaseTwoConfig {

    @Resource
    DatabaseTwoProperties databaseTwoProperties;

    @Bean("dataSourceTwo")
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(databaseTwoProperties.getJdbcUrl());
        druidDataSource.setUsername(databaseTwoProperties.getUsername());
        druidDataSource.setPassword(databaseTwoProperties.getPassword());
        druidDataSource.setDriverClassName(databaseTwoProperties.getDriverClassName());
        return druidDataSource;
    }

    @Bean("sqlSessionFactoryTwo")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSourceTwo") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/databasetwo/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("SqlSessionTemplateTwo")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactoryTwo") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("Txtwo")
    public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("dataSourceTwo") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

}
